﻿using BrnMall.Core;
using BrnMall.Services;
using BrnMall.Web.Framework;
using QD.PushManager.Domain;
using QD.PushManager.Manager;
using QIDong.WeApp.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using WeiTap.Restful;

namespace QIDong.WeApp.Controllers
{
    public class PushController : WebApi
    {
        static MallConfigInfo MallConfig = BMAConfig.MallConfig;//商城配置信息
        /// <summary>
        /// 获取推送信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public object PushList(int userId = 0, int page = 1)
        {
            var list = new List<PushProduct>();

            //获取推送用户(设置过推送时间)
            //获取推送用户(未设置推送时间)
            var company = CompanyManager.GetPushCompany(userId, page);
            if (company == null) return list;

            //检测当天是否已推送
            if (ProductLogManager.IsPush(userId, DateTime.Now))
                throw new Exception("今天已推送，不允许再推送");

            //获取推送设置

            //计算置顶产品数、产品数、文章数、
            int topCount = 0, productCount = 0, articleCount = 0;



            //获取即时信息(置顶产品)

            //获取订阅宝商品

            //获取新闻源

            //标签源不够，取新闻源补足

            //获取小程序商品
            return list;
        }

        /// <summary>
        /// 将小程序商品同步到订阅宝
        /// </summary>
        /// <param name="dyb_userid">订阅宝的会员ID</param>
        /// <param name="dyb_UserName">订阅宝的用户名</param>
        /// <returns></returns>
        public object SynProductToDyb(int dyb_userid, string dyb_UserName, int pageSize = 1000)
        {
            var uid = OAuths.GetUidByOpenIdAndServer(dyb_UserName, "dyb");
            if (uid < 1)
                throw new Exception("未找到小程序用户");

            var partUserInfo = Users.GetPartUserById(uid);
            if (partUserInfo == null)
                throw new Exception("未开通小程序店铺");

            var storeId = partUserInfo.StoreId;
            var count = 0;

            //获取小程序商品
            string condition = AdminProducts.AdminGetProductListCondition(storeId, 0, string.Empty, 0, 0, (int)ProductState.OnSale);
            var listProduct = AdminProducts.AdminGetProductList(pageSize, 1, condition);

            //获取关联记录
            var idList = ProductUnionManager.GetUnionIdList(dyb_userid, 1, 10000);
            //同步商品
            foreach (DataRow dr in listProduct.Rows)
            {
                var pid = Convert.ToInt32(dr["pid"]);
                if (idList.Contains(pid))
                {
                    //小程序商品
                    var productInfo = Products.GetProductById(pid);
                    //订阅宝商品
                    var dyb_product = FormatModel(productInfo, dyb_userid);
                    //订阅宝商品ID
                    var dyb_productid = ProductUnionManager.GetProductIdByUnionId(pid, 1);
                    dyb_product.ProductId = dyb_productid;
                    //更新订阅宝商品
                    int updateCount = ProductManager.UpdateByPush(dyb_product);
                    if (updateCount > 0)
                        ProductDetailManager.Update(new ProductDetail() { FK_ProductId = dyb_productid, Details = productInfo.Description });
                    else
                    {
                        dyb_productid = ProductManager.Add(dyb_product);
                        ProductDetailManager.Add(new ProductDetail() { FK_ProductId = dyb_productid, Details = productInfo.Description });
                    }                    
                    count++;
                }
                else
                {
                    //小程序商品
                    var productInfo = Products.GetProductById(pid);
                    //订阅宝商品
                    var dyb_product = FormatModel(productInfo, dyb_userid);

                    var dyb_productid = ProductManager.Add(dyb_product);
                    //新增内容
                    ProductDetailManager.Add(new ProductDetail() { FK_ProductId = dyb_productid, Details = productInfo.Description });
                    //新增关联记录
                    ProductUnionManager.Add(GetUnionProduct(dyb_userid, dyb_productid, pid));
                    count++;
                }
            }
            var model = new { count = count, remark = string.Format("导入了{0}个商品", count) };
            return model;
        }


        public object SynProductToDyb_old(int dyb_userid, string dyb_UserName, int pageSize = 1000)
        {
            var uid = OAuths.GetUidByOpenIdAndServer(dyb_UserName, "dyb");
            if (uid < 1)
                throw new Exception("未找到小程序用户");

            var partUserInfo = Users.GetPartUserById(uid);
            if (partUserInfo == null)
                throw new Exception("未开通小程序店铺");

            var storeId = partUserInfo.StoreId;
            var count = 0;

            //获取小程序商品
            var listProduct = Products.GetStoreClassProductList(pageSize, 1, 0, storeId, 0, 0, 0, 0);
            //获取关联记录
            var idList = ProductUnionManager.GetUnionIdList(dyb_userid, 1, 10000);
            //同步商品
            foreach (var item in listProduct)
            {
                if (idList.Contains(item.Pid))
                {
                    ////小程序商品
                    //var productInfo = Products.GetProductById(item.Pid);
                    ////订阅宝商品
                    //var dyb_product = FormatModel(productInfo, dyb_userid);
                    ////订阅宝商品ID
                    //var dyb_productid = ProductUnionManager.GetProductIdByUnionId(item.Pid, 1);
                    //dyb_product.ProductId = dyb_productid;
                    ////更新订阅宝商品
                    //ProductManager.Update(dyb_product);
                    //ProductDetailManager.Update(new ProductDetail() { FK_ProductId = dyb_productid, Details = productInfo.Description });
                    //count++;
                }
                else
                {
                    //小程序商品
                    var productInfo = Products.GetProductById(item.Pid);
                    //订阅宝商品
                    var dyb_product = FormatModel(productInfo, dyb_userid);

                    var dyb_productid = ProductManager.Add(dyb_product);
                    //新增内容
                    ProductDetailManager.Add(new ProductDetail() { FK_ProductId = dyb_productid, Details = productInfo.Description });
                    //新增关联记录
                    ProductUnionManager.Add(GetUnionProduct(dyb_userid, dyb_productid, item.Pid));
                    count++;
                }
            }

            var model = new { count = count, remark = string.Format("导入了{0}个商品", count) };
            return model;
        }

        Product FormatModel(BrnMall.Core.ProductInfo info, int userId)
        {
            return new Product()
            {
                UserId = userId,
                CategoryId = 0,
                Copyfrom = "",
                EditorId = 0,
                Tags = 0,
                MaxCharPerPage = 1,
                TemplateId = 0,
                EditorName = "",
                Keywords = "",
                PicUrl = string.Format("{0}/upload/store/{1}/product/show/source/{2}", MallConfig.ImageCDN, info.StoreId, info.ShowImg),
                Title = info.Name
            };
        }

        ProductUnion GetUnionProduct(int userid, int productid, int unionProductId)
        {
            return new ProductUnion()
            {
                UserId = userid,
                ProductId = productid,
                UnionProductId = unionProductId,
                Source = 1,
                AddTime = DateTime.Now
            };
        }

    }
}